Skip to content

[WIP] scripting interface - #276

Closed
BenWibking wants to merge 13 commits into
AMReX-Codes:mainfrom
BenWibking:scripting
Closed

BenWibking wants to merge 13 commits into
AMReX-Codes:mainfrom
BenWibking:scripting

Conversation

@BenWibking

@BenWibking BenWibking commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Adds a Qt-free analysis layer (src/analysis) and an amrexplorer Python package (nanobind, python/) so post-processing scripts can read AMReX plotfiles through the viewer's own C++ readers. This first PR covers the foundation: exact iteration over leaf cells, and parallel reductions over them.

Usage: docs/python-analysis.md.

What it provides

  • Leaf-cell plans and chunks.
    • Each leaf cell (a cell no finer level covers) appears exactly once, in a fixed order: levels coarsest first, grids in native FAB order.
    • Regions are half-open and select cells by center, so adjacent regions split cells between them without overlap.
    • Precision is tracked per level.
    • A plan is checked against the cache budget when it is made.
    • Derived fields are defined when the dataset opens and fail there if they don't resolve.
    • Chunks are copies that outlive the dataset.
  • Parallel map-reduce (amrexplorer.parallel):
    • Thread, process and MPI-partitioned execution over leaf-cell plans.
    • Each worker opens its own dataset handle, and only a bounded number of items are in flight at once.
    • Reductions are combined in plan order, so results are bit-identical to a serial run.
  • Block statistics: a grid listing and per-grid min/max computed from the decoded data.
  • Batch helpers: plotfile sequences, progress callbacks and cancellation tokens.
  • Packaging: pip install . through scikit-build-core, or -DAMREXPLORER_ENABLE_PYTHON=ON in a normal CMake build.

Smaller changes elsewhere:

  • The shared cache-budget default moves from src/qt to core/CacheConfig.hpp.
  • PlotfileDataset takes a derived-field policy.
  • FabValues exposes its payload as a span in its stored precision.

Deferred

These features are on the analysis-deferred branch, to be proposed in follow-up PRs:

  • tiles with ghost cells
  • surface-area helpers
  • conservative CIC particle deposition
  • headless rendering
  • exact projections and slices
  • particle chunks

Validation

  • tools/analysis_validation/run_comparisons.sh passes all 9 comparisons:
    • On a 20-level, 22 GB Quokka plotfile and on a Quokka galaxy plotfile, amrexplorer and yt select identical leaf cells with identical values.
    • examples/plotfile_fab_minmax.py produces per-FAB extrema byte-identical to Kangaroo's on synthetic plotfiles and on the real plotfile, including NaN cells.
  • A real-data comparison found an overflow bug, now fixed. The planner tested whether a region was empty by counting its cells, and on a 2^64-cell region the count wrapped to zero and the level was dropped. test_region_over_a_huge_domain_is_not_empty covers it.
  • tools/analysis_validation/benchmark_parallel.py measures the parallel speed-up.

Tests

  • New tests/python suite (40 tests), run by ctest as python_analysis.
  • New tests/integration/test_leaf_chunks.cpp, so builds without Python still test leaf-cell traversal.
  • The headless ctest suite (64 tests) passes. The Qt suite hasn't been run since the branch was cut down.

🤖 Generated with Claude Code

BenWibking and others added 13 commits September 28, 2026 16:48
Resolve gaps found in review of the design doc:
- Define a canonical leaf-cell order: levels ascending, grids along a
  Morton curve keyed on lower corners, cells in Fortran FAB order.
- Field arrays keep the plotfile dtype unless overridden by `dtype`;
  geometry arrays are always float64.
- Define cell_volume for 1-D, 2-D, and 3-D Cartesian plotfiles.
- Assume proper nesting, so coverage checks only the next finer level.
- Drop component indices; each plotfile variable is its own field.
- Add `max_bytes` (default 4 * target_bytes) as the explicit per-item
  allocation limit, and test its rejection in milestone 1.
- Drop the cancellation test from milestone 1; milestone 5 owns it.
- Build the example's cold mask once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add block metadata and statistics, sphere and cylinder
surface-intersection helpers, tiles with ghost cells, and particle CIC
deposition as later primitives, with milestones 6-9 that port the
corresponding Kangaroo plotfile scripts and compare against Kangaroo.
Name kangaroo/scripts/ in the goal, and point the leaf-chunk section at
the new tile API.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Make each leaf chunk exactly one FAB; drop target_bytes and windowed
  reads, and give max_bytes a fixed 1 GiB default.
- Use Kangaroo's tangent-plane approximation as the flux-surface
  reference, including analytic end-cap moments and face rules.
- Pad surface regions by the coarsest leaf cell's half-diagonal.
- Compute block extrema from decoded data, ignoring NaN, and report
  native FAB indices.
- Fill ghost cells from the finest coarser level that covers them.
- Add a particle mask to deposit_particles, follow Kangaroo's CIC
  boundary policy, and state conservation with dropped weight.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Narrow derived fields to the stored dtype when dtype=None.
- Fingerprint derived-field definitions in the plan and raise on read
  if one has changed.
- Drop max_bytes; reject items whose pinned inputs exceed the block-cache
  budget at planning time, estimating from the grown on-disk box.
- Run Kangaroo's exact intersection test before tangent-plane areas, and
  measure cylinder coordinates from the center.
- Include stored ghost cells in block extrema; all-NaN blocks report NaN.
- Make particle deposition conservative across block, coarse-fine, and
  domain boundaries instead of matching Kangaroo's dropped weight, and
  raise on non-finite particles.
- State that cell_volume is always present for supported geometries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Order grids within a level by native FAB index instead of Morton order.
- Add cache_bytes to open_plotfile, mapping to the C++ cache budget;
  raise on an invalid AMREXPLORER_CACHE_SIZE_MB and when
  set_cache_bytes cannot fit pinned blocks, and note the mapped-grid pool.
- Count derived-field blocks (float64, valid box, including chained
  inputs) in the planning-time cache estimate, using the stored dtype.
- Take derived definitions explicitly via open_plotfile(derived=...),
  raise on any that do not resolve, and drop the fingerprint check
  since definitions are fixed per dataset.
- Reject plan items read through a different dataset.
- Limit derived-field block extrema to the valid box.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Restore the previous cache budget on both pools when set_cache_bytes
  fails, so a failed call leaves the dataset unchanged.
- Pass DerivedFieldPolicy::Strict through the PlotfileDataset
  constructor instead of checking skipped definitions after opening.
- Specify per-axis chunk quantities as separate 1-D arrays.
- Accept only a per-chunk callable as the particle deposition mask.
- Port and validate the remaining Kangaroo plotfile scripts in
  milestones 1, 2, 4, and 5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Make leaf and particle chunks copies that hold no cache pins.
- Compute chunk geometry arrays lazily on first access.
- Default dtype to the widest stored dtype across levels.
- Replace the exact pinned-bytes model with a conservative upper bound.
- Make particle chunks one grid each and drop target_bytes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Implements docs/analysis-scripting-interface.md: a Qt-free analysis layer
(src/analysis) and the amrexplorer Python package (nanobind, python/).

- Exact leaf-cell plans and chunks: canonical order, half-open regions by
  cell center, per-level precision, planning-time cache-budget checks,
  strict derived fields, chunks that outlive the dataset.
- Complete particle attributes and stable ids, one chunk per grid.
- Parallel map-reduce over plan items: worker-local handles, bounded
  in-flight items, ordered reductions identical to serial.
- Exact projections, sampled and cell-average slices, per-block
  statistics, sphere and cylinder surface areas, ghost-cell tiles with
  FillPatch-style interpolation, conservative AMR-aware CIC deposition,
  and headless slice and volume rendering.
- Sequence helpers, cancellation tokens, progress callbacks, pip install.
- Ports of the yt and Kangaroo analysis scripts in python/examples, and
  tools/analysis_validation, which compares them with the originals on
  synthetic and real Quokka plotfiles (docs/analysis-validation.md).

The shared cache-budget default moves to core/CacheConfig.hpp, and
PlotfileDataset takes a derived-field policy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Drop the astrophysics-specific ports from python/examples, keeping
  plotfile_slice.py, plotfile_fab_minmax.py and plot_frames.py.
- Drop the validation helpers only those ports used, and trim
  run_comparisons.sh and test_examples.py to the kept scripts.
- Trim the validation doc to the comparisons the repository can rerun.
- Stop referencing the incite-2026 scripts and datasets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Drop docs/analysis-scripting-interface.md and
  docs/analysis-validation.md.
- Point the remaining references at docs/python-analysis.md and the
  validation tools, and drop the milestone labels from docstrings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Drop the example-script and rendering smoke tests.
- Fold the leaf-chunk request-error tests into one parametrized test.
- Drop the leaf partition test that test_parallel already covers, moving
  its out-of-range check there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Keep leaf-chunk plans and iteration, parallel map-reduce over leaf
cells, block statistics, sequence helpers, cancel tokens and progress
callbacks. Move tiles, surfaces, deposition, headless rendering,
projections, slices and particle chunks to the analysis-deferred branch,
with their bindings, tests, examples and validation tools, and restore
ParticleReader to the merge base.

Drop particle support from the test plotfile writer and turn the
particle fixture into a gas-only AMR fixture, since nothing here reads
particles any more.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@BenWibking

Copy link
Copy Markdown
Contributor Author

Superseded by a stack of smaller PRs, to be reviewed and merged in order:

  1. [Scripting] Generalize PlotfileDataset and the cache budget for analysis tools #289 Prepare PlotfileDataset and the cache budget for analysis
  2. [Scripting] Add iteration plans for leaf-cell chunks #285 Exact leaf-cell plans and chunks (C++)
  3. [Scripting] Add the amrexplorer Python package for batch analysis #286 The amrexplorer Python package (bindings)
  4. [Scripting] Add map-reduce parallel reductions over leaf cells #287 Parallel reductions and batch helpers
  5. [Scripting] Add block listing and per-block statistics #288 Block listing and per-block statistics
  6. [Scripting] Add manual validation tools for the analysis package #290 Validation tools

The deferred features (tiles, surfaces, deposition, rendering, projections, slices, particle chunks) are on the analysis-deferred branch of the fork for follow-up PRs.

@BenWibking BenWibking closed this Oct 29, 2026
WeiqunZhang pushed a commit that referenced this pull request Nov 4, 2026
…sis tools (#289)

Small changes to existing code that the analysis library (next PR)
needs. No new feature yet.

- **Cache budget in `core`.** The cache-budget default and
`AMREXPLORER_CACHE_SIZE_MB` parsing move from `src/qt/CacheConfig.hpp`
to `include/amrexplorer/core/CacheConfig.hpp`, so code without Qt can
share them. `src/qt/CacheConfig.hpp` now uses the core version.
- **Derived-field policy.** `PlotfileDataset` takes a
`DerivedFieldPolicy`:
  - The viewer keeps `Skip`.
- An unattended analysis passes `Strict`, so a definition that doesn't
resolve fails at open instead of silently dropping the field.
- **`derivedFieldProgram(field)`.** Exposes a derived field's compiled
program, so a caller can bound in advance which blocks a read will pin.
- **`FabValues` spans.** `FabValues::singleValues()` and
`doubleValues()` expose the payload in its stored precision, for callers
copying many values without dispatching on precision per value.

## Tests

- New `tests/integration/test_derived_field_policy.cpp`:
  - `Skip` installs what resolves and reports the rest.
  - `Strict` fails the open, naming the broken definition.
- `derivedFieldProgram` returns null for a stored field and the right
inputs for a derived one, and a derived block evaluates its program.
- `test_single_precision_plotfile.cpp` checks both span accessors for
float and double FABs.
- The headless ctest suite passes (63 tests).

## Stack

Part of a stack replacing #276. Review and merge in order; each PR shows
only its own layer.
1. #289 Prepare PlotfileDataset and the cache budget for analysis ← this
PR
2. #285 Exact leaf-cell plans and chunks (C++)
3. #286 The amrexplorer Python package (bindings)
4. #287 Parallel reductions and batch helpers

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
WeiqunZhang pushed a commit that referenced this pull request Nov 4, 2026
A Qt-free `src/analysis` library with an exact planner and reader for a
plotfile's **leaf cells**, the cells no finer level covers. This is the
core algorithm the Python package builds on.

- **Plans.** `planLeafChunks` partitions the leaf cells of a region into
one item per grid, in a fixed order: levels coarsest first, grids in
native FAB order.
- Covered coarse cells never appear, and every leaf cell appears exactly
once.
- Regions select cells by center, `lower <= center < upper`, so adjacent
regions split the cells between them.
  - Planning reads metadata only.
- **Precision.** Field values keep the widest precision any level stores
unless the plan asks for float32 or float64. Derived fields are
evaluated per block and follow the plan's dtype.
- **Cache budget.** Each item's worst-case cache use is checked against
the budget at planning, and again when reading. The error names the
item.
- **Chunks.** `readLeafChunk` copies an item's values out of the cache:
a chunk holds no cache pins and outlives the dataset. Geometry arrays
(indices, centers, widths, volumes) are computed on first use.
- **Errors.** Unknown fields, unsupported geometry or centering, invalid
regions and items planned on another dataset are `AnalysisError`.

## Review notes

`src/analysis/LeafChunks.cpp` is the file to read closely. The
covered-cell computation, region-to-index-box conversion and the
pinned-bytes estimate are where the guarantees come from.

## Tests

`tests/integration/test_leaf_chunks.cpp` runs on a two-level 2-D fixture
whose fine grid straddles a coarse grid boundary. It checks:
- exact partition, stored values, and the leaf cells tiling the domain
- the half-open region rule, and an empty plan outside the domain
- unknown, duplicate and non-finite requests are refused, as is
non-Cartesian geometry
- float32 narrowing and derived fields
- reading items repeatedly and in any order
- no pins after a read, and chunks outliving the dataset
- the planning-time and read-time budget checks
- cancellation, and items bound to their dataset

The headless ctest suite passes (64 tests).

## Stack

Part of a stack replacing #276. Review and merge in order; each PR shows
only its own layer.
1. #289 Prepare PlotfileDataset and the cache budget for analysis
2. #285 Exact leaf-cell plans and chunks (C++) ← this PR
3. #286 The amrexplorer Python package (bindings)
4. #287 Parallel reductions and batch helpers

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
WeiqunZhang pushed a commit that referenced this pull request Nov 17, 2026
The `amrexplorer` Python package: nanobind bindings over the leaf-cell
planner and reader from the previous PR, plus a small pure-Python
wrapper and build plumbing. Most of this PR is mechanical glue. The
Python tests are the clearest statement of the API.

- **`open_plotfile(path, derived=..., cache_bytes=...)`** returns a
`Dataset` usable as a context manager. Derived-field definitions use
`Strict`, so a bad one fails at open.
- **Plans and chunks.** `plan_leaf_chunks` returns a sequence of items,
and `read_leaf_chunk` returns a chunk.
- A chunk is a mapping of read-only NumPy arrays that keep their memory
alive, so they outlive the chunk and the dataset.
  - Geometry (`x`, `dx`, `i`, `cell_volume`, ...) is computed lazily.
  - `leaf_cells()` plans and reads in one loop.
- **`CancelToken`** stops a read in progress. Analysis, cache-budget,
read, closed-dataset and cancellation errors map to Python exceptions.
- **Build.**
- `-DAMREXPLORER_ENABLE_PYTHON=ON` builds the module into
`<build>/python`.
- `pip install .` builds the module alone through scikit-build-core
(`pyproject.toml`).
- ctest runs the pytest suite as `python_analysis` when pytest is
installed.
- **Docs.** `docs/python-analysis.md` (installing and leaf cells) and
`docs/building.md`.

## Review notes

- `python/src/module.cpp` (~540 lines) is type conversion: dicts and
boxes, NumPy views kept alive by capsules, GIL release around reads, and
closed-dataset checks.
- `python/amrexplorer/_dataset.py` is property accessors and the
Mapping/Sequence protocols over the native objects.
- Both are worth skimming, not reading line by line.

## Tests

- `tests/python/test_leaf_chunks.py` (25 tests) checks every contract
against an independent NumPy reconstruction of 1-D, 2-D and 3-D fixture
plotfiles. It includes a region over a 2^64-cell domain, a regression
test for an overflow found on real data.
- `tests/python/plotfile_writer.py` writes AMReX-layout plotfiles
(per-level precision, stored ghost cells, version-1 and version-2 FAB
headers) for these and later tests.
- The headless ctest suite passes (65 tests, `python_analysis` among
them).

## Stack

Part of a stack replacing #276. Review and merge in order; each PR shows
only its own layer.
1. #289 Prepare PlotfileDataset and the cache budget for analysis
2. #285 Exact leaf-cell plans and chunks (C++)
3. #286 The amrexplorer Python package (bindings) ← this PR
4. #287 Parallel reductions and batch helpers

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant